<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="update-avatar-head">
    <CommonHead title="修改用户头像"/>
  </header>

  <!--头: 上传图片-->
  <section class="update-avatar-body">
    <p>点击图片上传你的新头像</p>
    <van-field name="uploader">

      <template #input>

        <!--上传控件: 双绑头像文件，最大数量限制，前端上传前触发，前端上传后触发-->
        <van-uploader v-model="avatarFile" :max-count="1" style="margin: auto;"
                      :after-read="uploadAvatar" :before-read="checkAvatar">

          <!--图标: 尺寸，类型-->
          <van-icon size="100" name="photo"/>

        </van-uploader>

      </template>

    </van-field>
  </section>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {UPLOAD_AVATAR} from "@/api/user";
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 头像文件
let avatarFile = shallowRef();

/* ==================== method ==================== */

// method: 上传文件之前，检查文件的类型和大小
function checkAvatar(file) {

  // 检查文件类型
  if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
    showFailToast('请上传JPEG或PNG格式图片');
    return false;
  }

  // 检查文件大小
  if (file.size > 5000 * 1024) {
    showFailToast('文件大小不能超过500KB');
    return false;
  }

  // 放行
  return true;
}

// method: 上传头像
function uploadAvatar(e){

  // 上传二进制图片需要使用FormData对象
  let formData = new FormData();
  formData.append('avatarFile', e.file);

  // 同步调用修改用户头像的接口
  UPLOAD_AVATAR(formData).then(result => {
    let resp = result['data'];
    if (resp.code === SUCCESS) {
      showSuccessToast('头像上传成功');
      setTimeout(() => router.push('/Personal'), 1000);
    } else {
      showFailToast(resp.message + ': ' + resp.data);
    }
  }).catch(err => console.error(err));
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});

</script>

<style scoped lang="scss">

</style>